package com.yummy.web.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.NestedServletException;

import com.yummy.convention.exception.BusinessException;
import com.yummy.convention.http.Response;

public class GlobalExceptionFilter implements Filter{
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		try{
			chain.doFilter(request, response);
		} catch (Exception e) {
			if(e instanceof BusinessException) {
				sendBusinessResponse((BusinessException)e,request,response);
				return;
			}
			logger.error(e.getMessage(),e);
			if(e instanceof NestedServletException) {
				Throwable e1 = e.getCause();
				if(e1 instanceof BusinessException) {
					sendBusinessResponse((BusinessException)e1,request,response);
					return;
				}
				sendInnerErrorResponse(request,response);
				return;
			}else {
				sendInnerErrorResponse(request,response);
			}
		}
	}

	private void sendInnerErrorResponse(ServletRequest request, ServletResponse response) throws UnsupportedEncodingException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		response.getOutputStream().write(Response.failure().toString().getBytes("UTF-8"));
		response.flushBuffer();
	}

	private void sendBusinessResponse(BusinessException e, ServletRequest request, ServletResponse response) throws UnsupportedEncodingException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		Response<?> content = e.getErrorCode() == null
				? Response.failure(e.getMessage())
				: Response.failure(e.getErrorCode(), e.getMessage());
		response.getOutputStream().write(content.toString().getBytes("UTF-8"));
		response.flushBuffer();
	}


}
